<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="配置名" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入配置名"
          clearable
          size="small"
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="别名" prop="key">
        <el-input
          v-model="queryParams.key"
          placeholder="请输入别名"
          clearable
          size="small"
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="系统内置" prop="isInner">
        <el-select v-model="queryParams.isInner" placeholder="系统内置" clearable size="small">
          <el-option
            v-for="dict in isInnerOptions"
            :key="dict.id"
            :label="dict.name"
            :value="dict.val"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="是否允许外界访问" prop="isVisit">
        <el-select v-model="queryParams.isVisit" placeholder="是否允许外界访问" clearable size="small">
          <el-option
            v-for="dict in isInnerOptions"
            :key="dict.id"
            :label="dict.name"
            :value="dict.val"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间">
        <el-date-picker
          v-model="dateRange"
          size="small"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="cyan" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['/sys/config/save']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['/sys/config/updateById']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['/sys/config/remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['/sys/config/export']"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-refresh"
          size="mini"
          @click="handleClearCache"
          v-hasPermi="['/sys/config/clear']"
        >清理缓存</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="configList" @selection-change="handleSelectionChange" :border="true">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="配置名" align="center" prop="name" :show-overflow-tooltip="true" />
      <el-table-column label="别名" align="center" prop="key" :show-overflow-tooltip="true" />
      <el-table-column label="参数值" align="center" prop="val" :show-overflow-tooltip="true" />
      <el-table-column label="类型" align="center" prop="type" :formatter="typeFormat" />
      <el-table-column label="系统内置" align="center" prop="isInner" :formatter="isInnerFormat" />
      <el-table-column label="备注" align="center" prop="remark" :show-overflow-tooltip="true" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['/sys/config/updateById']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['/sys/config/remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改参数配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="配置名" prop="name">
          <el-input v-model="form.name" placeholder="请输入配置名" />
        </el-form-item>
        <el-form-item label="别名" prop="key" v-if="!form.id">
          <el-input v-model="form.key" placeholder="请输入别名" />
        </el-form-item>
        <el-form-item label="别名" prop="key" v-if="form.id">
          <el-input v-model="form.key" placeholder="请输入别名" :disabled="true" />
        </el-form-item>
        <el-form-item label="类型" prop="type">
          <el-select v-model="form.type" placeholder="类型" clearable size="small">
            <el-option
              v-for="dict in typeOptions"
              :key="dict.id"
              :label="dict.name"
              :value="dict.val"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="参数值" prop="val" v-if="form.type == eConfigType.IMG.code &&  form.isInner == eYesNo.YES.code">
          <uploadImage :type="[eFileType.IMG]" v-model="form.val"/>
        </el-form-item>
        <el-form-item label="参数值" prop="val" v-else-if="form.type == eConfigType.VIDEO.code &&  form.isInner == eYesNo.YES.code">
          <uploadImage :type="[eFileType.VIDEO]" v-model="form.val"/>
        </el-form-item>
        <el-form-item label="参数值" prop="val" v-else-if="form.type == eConfigType.FILE.code &&  form.isInner == eYesNo.YES.code">
          <uploadImage :type="[eFileType.FILE]" v-model="form.val"/>
        </el-form-item>
        <el-form-item label="参数值" prop="val" v-else-if="form.type == eConfigType.INT.code || form.type == eConfigType.DOUBLE.code || form.type == eConfigType.TOTAL.code">
          <el-input v-model="form.val" placeholder="请输入参数值" />
        </el-form-item>
        <el-form-item label="参数值" prop="val" v-else-if="form.type == eConfigType.BOOLEAN.code">
          <el-switch
            v-model="form.val"
            :active-value="'true'"
            :inactive-value="'false'"
            active-color="#13ce66"
            inactive-color="#ff4949">
          </el-switch>
        </el-form-item>
        <el-form-item label="参数值" prop="val" v-else>
          <el-input v-model="form.val" placeholder="请输入参数值" />
        </el-form-item>
        <el-form-item label="数字类型" prop="typeNum" v-if="form.type == eConfigType.INT.code || form.type == eConfigType.DOUBLE.code || form.type == eConfigType.TOTAL.code">
          <el-select v-model="form.typeNum" placeholder="类型" clearable size="small">
            <el-option
              v-for="dict in typeNumOptions"
              :key="dict.id"
              :label="dict.name"
              :value="dict.val"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="是否允许为0" prop="typeNumIsZero" v-if="(form.type == eConfigType.INT.code || form.type == eConfigType.DOUBLE.code || form.type == eConfigType.TOTAL.code) && form.typeNum != eConfigTypeNum.UNLIMITED.code">
          <el-switch
            v-model="form.typeNumIsZero"
            active-color="#13ce66"
            inactive-color="#ff4949">
          </el-switch>
        </el-form-item>
        <el-form-item label="系统内置" prop="isInner">
          <el-radio-group v-model="form.isInner">
            <el-radio
              v-for="dict in isInnerOptions"
              :key="dict.id"
              :label="dict.val"
            >{{dict.name}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="是否允许外界访问" prop="isVisit">
          <el-switch
            v-model="form.isVisit"
            :active-value="eYesNo.YES.code"
            :inactive-value="eYesNo.NO.code"
            active-color="#13ce66"
            inactive-color="#ff4949">
          </el-switch>
        </el-form-item>
        <el-form-item label="顺序" prop="sortNum">
          <el-input v-model="form.sortNum" placeholder="请输入顺序" type="number" :change="sortNumFormat()" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { addConfig, updateConfig, listConfig, delConfig, getConfig, exportConfig, clearCache } from "@/api/system/config";
import UploadImage from '@/components/UploadImageList';
import { PAGE_SIZE, SORT_NUM } from "@/constant/constant";
import { GENERAL_YES_NO, FILE_TYPE, CONFIG_TYPE, CONFIG_TYPE_NUM } from "@/enum/enum";

export default {
  name: "Config",
  components: {
    UploadImage,
  },
  data() {
    return {
      // 枚举属性
      // 通用是否
      eYesNo: GENERAL_YES_NO,
      // 文件类型
      eFileType: FILE_TYPE,
      // 系统配置类型
      eConfigType: CONFIG_TYPE,
      // 系统配置数字类型
      eConfigTypeNum: CONFIG_TYPE_NUM,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 参数表格数据
      configList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 类型数据字典
      typeOptions: [],
      // 数字类型数据字典
      typeNumOptions: [],
      // 是否内置数据字典
      isInnerOptions: [],
      // 日期范围
      dateRange: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: PAGE_SIZE,
        name: undefined,
        key: undefined,
        isInner: undefined,
        isVisit: undefined
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        name: [
          { required: true, message: "配置名不能为空", trigger: "blur" }
        ],
        key: [
          { required: true, message: "别名不能为空", trigger: "blur" }
        ],
        val: [
          { required: true, message: "参数值不能为空", trigger: "blur" }
        ],
        type: [
          { required: true, message: "类型不能为空", trigger: "blur" }
        ],
        typeNum: [
          { required: true, message: "数字类型不能为空", trigger: "blur" }
        ],
        typeNumIsZero: [
          { required: true, message: "是否允许为0不能为空", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getList();
    this.getDicts("general_yes_no").then(response => {
      response.data.forEach(element => {
        element.val = parseInt(element.val)
      });
      this.isInnerOptions = response.data;
    });
    this.getDicts("config_type").then(response => {
      response.data.forEach(element => {
        element.val = parseInt(element.val)
      });
      this.typeOptions = response.data;
    });
    this.getDicts("config_type_num").then(response => {
      response.data.forEach(element => {
        element.val = parseInt(element.val)
      });
      this.typeNumOptions = response.data;
    });
  },
  methods: {
    /** 查询参数列表 */
    getList() {
      this.loading = true;
      listConfig(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
          this.configList = response.data;
          this.total = response.page.total;
          this.loading = false;
        }
      );
    },
    // 参数类型字典翻译
    typeFormat(row, column) {
      return this.selectDictLabel(this.typeOptions, row.type);
    },
    // 参数系统内置字典翻译
    isInnerFormat(row, column) {
      return this.selectDictLabel(this.isInnerOptions, row.isInner);
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        name: undefined,
        key: undefined,
        val: undefined,
        type: this.eConfigType.STRING.code,
        typeNum: this.eConfigTypeNum.UNLIMITED.code,
        typeNumIsZero: true,
        isInner: this.eYesNo.YES.code,
        isVisit: this.eYesNo.NO.code,
        sortNum: SORT_NUM,
        remark: undefined
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加参数";
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!=1
      this.multiple = !selection.length
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getConfig(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改参数";
      });
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != undefined) {
            updateConfig(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addConfig(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除参数编号为"' + ids + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delConfig(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.addDateRange(this.queryParams, this.dateRange);
      this.$confirm('是否确认导出所有参数数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return exportConfig(queryParams);
        }).catch(() => {});
    },
    /** 清理缓存按钮操作 */
    handleClearCache() {
      clearCache().then(response => {
        this.msgSuccess("清理成功");
      });
    },
    /** 限制只能输入正整数 */
    sortNumFormat(){
      let sortNum = this.form.sortNum;
      if(sortNum){
        sortNum = sortNum.toString();
        let d = sortNum.indexOf('.');
        if(d > -1){
          this.form.sortNum = sortNum.substring(0,d);
        }
      }
    }
  }
};
</script>